import os
import re
from pymysql import *
# 导入url编码模块
import urllib.parse
# 添加日志模块
import logging

# 测试使用
# print(os.path.abspath(__file__))  # 显示当前文件的地址
# print(os.getcwd())  # 显示主程序入口的地址

# 定义一个字典来储存方法的引用，key=访问路径，value=函数引用
route_dict = dict()


def route(url):
    def set_func(func):
        # 将所有函数的引用保存到字典中，后续调用
        route_dict[url] = func

        def call_func(*args, **kwargs):
            return func(*args, **kwargs)

        return call_func

    return set_func


@route(r"/index.py")
def index(info, ret):
    with open(info["template"] + "/index.html", encoding="utf-8") as f:
        content = f.read()

        # 链接数据库
        con = connect(host='localhost', port=3306, database='stock_db', user='root', password='root', charset='utf8')
        cursor = con.cursor()
        sql = "select * from info;"
        cursor.execute(sql)
        # 查询数据
        data_from_mysql = cursor.fetchall()

        html = ""
        # 拼接html
        for tr_data in data_from_mysql:
            # print(tr_data)
            html += "<tr>"
            for td_data in tr_data:
                html += f"<td>{td_data}</td>"

            html += """<td>
                        <input type="button" value="添加" id="toAdd" name="toAdd" systemidvaule="%s">
                    </td>
                    """ % tr_data[1]
            html += "</tr>"
        # print(html)
        content = re.sub(r"\{%content%\}", html, content)
        cursor.close()
        con.close()

        return content


@route(r"/center.py")
def center(info, ret):
    with open(info["template"] + "/center.html", encoding="utf-8") as f:
        content = f.read()

        # 链接数据库
        con = connect(host='localhost', port=3306, database='stock_db', user='root', password='root', charset='utf8')
        cursor = con.cursor()
        sql = "select i.code,i.short,i.chg,i.turnover,i.price,i.highs,f.note_info from info as i inner join focus as f on i.id=f.info_id;"
        cursor.execute(sql)
        # 查询数据
        data_from_mysql = cursor.fetchall()

        html = ""
        # 拼接html
        for tr_data in data_from_mysql:
            # print(tr_data)
            html += "<tr>"
            for td_data in tr_data:
                html += f"<td>{td_data}</td>"

            html += f"""<td>
                            <a type="button" class="btn btn-default btn-xs" href="/update/{tr_data[0]}.py"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> 修改 </a>
                        </td>
                        <td>
                            <input type="button" value="删除" id="toDel" name="toDel" systemidvaule="{tr_data[0]}">
                        </td>
                    """
            html += "</tr>"
        content = re.sub(r"\{%content%\}", html, content)
        cursor.close()
        con.close()
        return content


@route(r"/add/(\d+).py")
def add(info, ret):
    code = ret.group(1)
    # 链接数据库
    con = connect(host='localhost', port=3306, database='stock_db', user='root', password='root', charset='utf8')
    cursor = con.cursor()
    sql = "SELECT * FROM `info` WHERE CODE = %s; "
    cursor.execute(sql, (code,))
    reslut = cursor.fetchone()
    # 如果没有找到，表示选择的股票码有误
    if not reslut:
        cursor.close()
        con.close()
        return "选择的的股票码有误"
    # 查询是否已经关注过此股票
    sql = " select * from info as i inner join focus as f on i.id=f.info_id where i.code=%s;"
    cursor.execute(sql, (code,))
    reslut = cursor.fetchone()
    if reslut:
        cursor.close()
        con.close()
        return "选择的的股票已经关注过，请重新选择"

    # 添加股票关注
    sql = " insert into focus (info_id) select id from info where code=%s;"
    cursor.execute(sql, (code,))
    # 提交数据库
    con.commit()
    cursor.close()
    con.close()
    return "关注成功!!!"


@route(r"/del/(\d+).py")
def del_info(info, ret):
    code = ret.group(1)
    # 链接数据库
    con = connect(host='localhost', port=3306, database='stock_db', user='root', password='root', charset='utf8')
    cursor = con.cursor()
    sql = "SELECT * FROM `info` WHERE CODE = %s; "
    cursor.execute(sql, (code,))
    reslut = cursor.fetchone()
    # 如果没有找到，表示选择的股票码有误
    if not reslut:
        cursor.close()
        con.close()
        return "选择的的股票码有误"
    # 查询是否已经关注过此股票
    sql = " select * from info as i inner join focus as f on i.id=f.info_id where i.code=%s;"
    cursor.execute(sql, (code,))
    reslut = cursor.fetchone()
    # 如果没有关注将不能取消关注
    if not reslut:
        cursor.close()
        con.close()
        return "选择的的股票没有关注过，请重新选择"

    # 单数股票关注
    sql = " delete from focus where info_id = (select id from info where code=%s);"
    cursor.execute(sql, (code,))
    # 提交数据库
    con.commit()
    cursor.close()
    con.close()
    return "取消成功!!!"


# 显示修改页面
@route(r"/update/(\d+).py")
def update(info, ret):
    with open(info["template"] + "/update.html", encoding="utf-8") as f:
        content = f.read()

    code = ret.group(1)
    # 链接数据库
    con = connect(host='localhost', port=3306, database='stock_db', user='root', password='root', charset='utf8')
    cursor = con.cursor()
    # 查询是否已经关注过此股票,
    sql = " SELECT note_info FROM `info` AS i INNER JOIN focus AS f ON i.id=f.info_id WHERE i.code=%s;"
    # print(sql, code)
    cursor.execute(sql, (code,))
    note_info = cursor.fetchone()
    # 如果有关注将进行修改展示
    if not note_info:
        return "选择的的股票没有关注过，无法修改，请重新选择"

    # print(content)
    content = re.sub(r"\{%code%\}", code, content)
    content = re.sub(r"\{%note_info%\}", note_info[0], content)
    cursor.close()
    con.close()
    return content


# 修改备注
@route(r"/update/(\d+)/(.*).py")
def update_info(info, ret):
    code = ret.group(1)
    note_info = ret.group(2)
    # 由于前端传过来的数据是被编码过，所以此处需要解码
    note_info = urllib.parse.unquote(note_info)
    # 链接数据库
    con = connect(host='localhost', port=3306, database='stock_db', user='root', password='root', charset='utf8')
    cursor = con.cursor()
    # 查询是否已经关注过此股票,
    sql = " UPDATE focus  SET note_info = %s WHERE info_id = (SELECT id FROM `info` WHERE CODE=%s);"
    cursor.execute(sql, (note_info, code))
    # 提交
    con.commit()
    cursor.close()
    con.close()
    return "修改成功"


def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8')])
    filename = environ["PATH_INFO"]
    # 添加日志功能
    logging.basicConfig(level=logging.INFO,
                        filename='./log.txt',
                        filemode='a',
                        format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')

    logging.info("访问的是，%s" % filename)
    # 这里就直接使用文件名来通过字典映射出对应的函数引用执行函数
    # 循环存储的字典（字典中包含所有执行方法的引用）
    try:
        for url, func in route_dict.items():
            # 找到匹配的访问路径
            ret = re.match(url, filename)
            if ret:
                # 根据字典中的对应的值来执行方法
                return route_dict[url](environ["info"], ret)
        else:
            # 添加日志功能
            logging.warning("没有对应的函数....")
            return "请求的url(%s)没有对应的函数...." % filename
    except Exception as error:
        print(error)
        return "没有找到该资源"
